package com.dili.dd.gpi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 全局序列生成器
 * User: zhaoYuan
 * Date: 2015/1/7
 * Time: 16:05
 */
public class SequenceGenerator {
    private static final Logger logger = LoggerFactory.getLogger(SequenceGenerator.class);

    private AtomicLong id;

    private static SequenceGenerator instance = null;

    private SequenceGenerator(long id) {
        logger.info("Init SequenceGenerator, initial sequence is : {}." ,id);
        this.id = new AtomicLong(id);
    }


    public long incrementAndGet(){
        return id.incrementAndGet();
    }

    public long get(){
        return id.get();
    }

    public static SequenceGenerator getInstance(long initialValue){
        if (instance == null){
            init(initialValue);
        }
        return instance;
    }

    private synchronized static void init(long initialValue){
       if(instance == null){
           instance = new SequenceGenerator(initialValue);
       }
    }

}
